package com.unknown.world

import grails.converters.JSON
import grails.persistence.Entity

import com.unknown.BaseEntity

class Room extends BaseEntity {

	static {
		JSON.registerObjectMarshaller(Room){
			def map = [:]
			map['id'] = it.entityId
			map['name'] = it.name
			map['description'] = it.description
			map['exits'] = it.exits
			map['tiles'] = it.tiles
			return map;
		}
	}
		
	static hasMany = [exits:Exit, tiles:RoomTile, cells:Room]
	static hasOne  = [origin:Room]
	
	static constraints = {
		name(empty:false)
		description(nullable:true)
	}
	
	String name
	String description
	
	int row
	int column
	
	static Room findNeighbor(Room origin, int column, int row){
		def criteria = Room.createCriteria()
		def results = criteria {
			and{
				eq("origin", origin)
				eq("column", column)
				eq("row", row)
			}	
		}
		if( results && results.size() > 0 )
			return results[0]
		return null
	}
	
	public static Room createGrid(int rows, int cols, Room room){
		if( !room.tiles ) room.tiles = [];
		for(int row =0; row < rows; row ++){
			for(int col=(row%2); col < cols; col+=2){
				def tile = new RoomTile(col:col, row:row, tileId:'tiles/hex_grid_n.png');
				if( !room.tiles.contains(tile) )
					room.tiles.add(tile);
			}
		}
		return room
	}
	
}
